package net.xdclass.onlinexdclass.service.impl;

import lombok.extern.slf4j.Slf4j;
import net.xdclass.onlinexdclass.config.CacheKeyManager;
import net.xdclass.onlinexdclass.mapper.VideoBannerMapper;
import net.xdclass.onlinexdclass.mapper.VideoMapper;
import net.xdclass.onlinexdclass.model.entity.Video;
import net.xdclass.onlinexdclass.model.entity.VideoBanner;
import net.xdclass.onlinexdclass.service.VideoService;
import net.xdclass.onlinexdclass.templates.GuavaBaseCacheTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ExecutionException;

@Slf4j
@Service
public class VideoServiceImpl implements VideoService {

    @Autowired
    private VideoMapper videoMapper;

    @Autowired
    private VideoBannerMapper videoBannerMapper;

    @Autowired
    private GuavaBaseCacheTemplate guavaBaseCacheTemplate;

    @Override
    public List<Video> videoList() {

        try {
            Object cacheObject = guavaBaseCacheTemplate.getTenSecondsCache().get(CacheKeyManager.INDEX_VIDEO_KEY, () -> {
                List<Video> videolist = videoMapper.videoList();
                log.info("从数据库里面找轮播图列表");
                return videolist;
            });

            if (cacheObject instanceof List) {
                log.info("从guava缓存里面找轮播图列表");
                return (List<Video>) cacheObject;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }

    @Override
    public List<VideoBanner> listBanner() {

        try {
            //第一个参数是缓存的key，第二个参数是回调函数传入lambda表达式
            Object cacheObject = guavaBaseCacheTemplate.getTenSecondsCache().get(CacheKeyManager.INDEX_BANNER_KEY, () -> {
                List<VideoBanner> videoBanners = videoBannerMapper.listVideoBanner();
                log.info("从数据库里面找轮播图列表");
                return videoBanners;
            });

            if (cacheObject instanceof List) {
                log.info("从guava缓存中找轮播图列表");

                return (List<VideoBanner>) cacheObject;
            }
        } catch (ExecutionException e) {
            e.printStackTrace();
        }


        return null;
    }

    //@Cacheable以键值对的形式存储方法返回值，键是key的值
    @Override
    @Cacheable(value = "emp", key = "targetClass + MethodName + #id")
    public Video findDetailById(Integer id) {

        String videoCacheKey = String.format(CacheKeyManager.VIDEO_DETAIL, id);

        try {

            Object detaVideo = guavaBaseCacheTemplate.getOnHourCache().get(videoCacheKey, () -> {

                Video detailById = videoMapper.findDetailById(id);

                return detailById;

            });

            if (detaVideo instanceof Video) {
                return (Video) detaVideo;
            }

        } catch (Exception e) {

        }

        return null;
    }
}
